package com.project.finance.common.cosconfig;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.CreateBucketRequest;
import com.qcloud.cos.region.Region;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Auther: 贺谋昌
 * @Date: 2019/12/4 17:20
 * @Description:
 */
@Component
public class OCSConfig {
    /**
     * 初始化客户端
     *
     * @return
     */
    @Bean
    public COSClient getOCSClient() {
// 1 初始化用户身份信息（secretId, secretKey）。
        String secretId = "AKID5yd4Fk4D7qJZbNrKTNIyOYVaP5YlOiU1";
        String secretKey = "TgfQcZKp47uWwBC2cw33x1qRoxqWw62i";
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-chengdu");
        ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    /**
     * 获取到存储桶
     *
     * @return
     */
    @Bean
    public Bucket getBucket() {
        COSClient cosClient=getOCSClient();
        List<Bucket> buckets = cosClient.listBuckets();
        Bucket bucketResult = null;
        for (Bucket bucket : buckets) {
            String name = bucket.getName();
            if (name.equals("farmimg-1251492284")) {
                bucketResult = bucket;
                break;
            }
        }
        if (bucketResult != null) {
            return bucketResult;
        }
        String myBucket = "farmimg-1251492284"; //存储桶名称，格式：BucketName-APPID
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(myBucket);
// 设置 bucket 的权限为 PublicRead(公有读私有写), 其他可选有私有读写, 公有读写
        createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        try {
            bucketResult = cosClient.createBucket(createBucketRequest);
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }

        return bucketResult;
    }
}
